import Vue from 'vue'
import VueRouter from 'vue-router'
// 导入登录组件  @表示src
import Login from '@/views/Login.vue'
// 导入首页组件
import Home from '../views/home/Home.vue'
import Welcome from '../views/home/Welcome.vue'
import Users from '../views/home/Users.vue'
import Roles from '../views/power/Roles.vue'
import Rights from '../views/power/Rights.vue'
import List from '../views/goods/List.vue'
import Categories from '../views/goods/Categories.vue'
import Params from '../views/goods/Params.vue'
import AddGood from '../views/goods/AddGood.vue'
import Order from '../views/order/Orders.vue'
import Reports from '../views/report/Reports.vue'

Vue.use(VueRouter)

const routes = [
  { path: '/', redirect: '/login' },
  { path: '/login', component: Login },
  { path: '/home',
    component: Home, 
    children: [{ path: '/welcome', component: Welcome },
               { path: '/users', component: Users },
               { path: '/roles', component: Roles },
               { path: '/rights', component: Rights },
               { path: '/goods', component: List },
               { path: '/params', component: Params },
               { path: '/categories', component: Categories },
               { path: '/goods/add', component: AddGood },
               { path: '/orders', component: Order },
               { path: '/reports', component: Reports }],
    redirect: '/welcome'
  },
]

const router = new VueRouter({
  routes
})

// 挂载路由导航守卫，防止用户没有登录直接进入其他页面
router.beforeEach((to, from, next) => {
  // to 参数表示将要访问的路径
  // from 参数表示从哪个路径跳转过来的
  // next 是一个函数，表示放行，可以通过路由来跳转页面了
    // next() 放行  next('/login') 强制跳转
  if (to.path === '/login') { return next(); }
  // 获取 token
  const tokenStr = window.sessionStorage.getItem('token');
  if (!tokenStr) {  return next('/login');  }
  next();
  
})

export default router
